#include "interrupt.h"
#include "led.h"
#include "s3c2440.h"
#include "timer.h"
#include "type.h"
#include <stdio.h>

void register_irq(int irq, irq_func fp) {
  irq_array[irq] = fp;
  INTMSK &= ~(1 << irq);
}

void interrupt_init(void) {
  INTMSK &= ~((1 << 0) | (1 << 2) | (1 << 5));
  INTMSK &= ~(1 << 10);
}

void key_eint_init(void) {
  GPGCON &= ~((3 << 22) | (3 << 6));
  GPGCON |= ((2 << 22) | (2 << 6));

  GPFCON &= ~((3 << 0) | (3 << 4));
  GPFCON |= ((2 << 0) | (2 << 4));

  EXTINT0 |= (7 << 0) | (7 << 8);
  EXTINT1 |= (7 << 12);
  EXTINT2 |= (7 << 12);

  EINTMASK &= ~((1 << 11) | (1 << 19));
}

void key_eint_irq(int irq) {
  uint val = EINTPEND;
  uint val1 = GPFDAT;
  uint val2 = GPGDAT;

  if (irq == 0) {
    led_switch(1, val1);
  } else if (irq == 2) {
    led_switch(2, val1);
  } else if (irq == 5) {
    if (val & (1 << 11)) {
      led_switch(3, val2);
    } else if (val & (1 << 19)) {
      led_switch(4, val2);
    }
  }
  EINTPEND = val;

  register_irq(0, key_eint_irq);
  register_irq(2, key_eint_irq);
  register_irq(5, key_eint_irq);
}

void handle_irq(void) {
  int bit = INTOFFSET;

  // if (bit == 0 || bit == 2 || bit == 5) {
  //   key_eint_irq(bit);
  // } else if (bit == 10) {
  //   timer_irq();
  // }

  irq_array[bit](bit);

  SRCPND = (1 << bit);
  INTPND = (1 << bit);
}
